package com.how.config;

import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;

import java.util.LinkedList;
import java.util.List;

public class ConsoleTableRuleConfig {

    static final String DATABASE = "console";

    public static List<TableRuleConfiguration> getTableRuleConfigurations() {
        List<TableRuleConfiguration> tableRuleConfigs = new LinkedList<>();

        String actualDataNodes = DATABASE.concat("$->{0..1}.").concat("leads_user").concat("$->{0..1}");
        TableRuleConfiguration ruleConfiguration = new TableRuleConfiguration(
                "leads_user", actualDataNodes);
        // 分表策略
        String tableAlgorithmExpression = "leads_user".concat("$->{id % 2}");
        ruleConfiguration.setTableShardingStrategyConfig(
                new InlineShardingStrategyConfiguration("id", tableAlgorithmExpression));

        // 分库策略
        String dataBaseAlgorithmExpression = DATABASE.concat("$->{id % 2}");
        ruleConfiguration.setDatabaseShardingStrategyConfig(
                new InlineShardingStrategyConfiguration("id", dataBaseAlgorithmExpression));
//        ruleConfiguration.setDatabaseShardingStrategyConfig(new NoneShardingStrategyConfiguration());

        // 指定表的主键生成策略为SNOWFLAKE
        ruleConfiguration.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE", "id"));

        tableRuleConfigs.add(ruleConfiguration);

        return tableRuleConfigs;
    }
}